import React from 'react';
import PropTypes from 'prop-types';
import {getDetail} from './api';
import styles from './style.css';
import {hasPermissions, uuid} from './utils';
import {PERMISSIONS} from './constants';
import {newOrUpdateOrderValidator, addOrUpdateValidator} from './validator';
import {Form, Spin, Card, Button, Row, Col, Table, Popconfirm, message, Alert} from 'antd';
import {FORM_OPTIONS, FIXED_COLUMN_WIDTH, DATETIME_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import FormItem from 'antd/lib/form/FormItem';
import TextInput from 'Shared/components/TextInput';
import {injectIntl, formatMessage} from './intl';
import WrappedInputNumber from '../common/WrappedInputNumber';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import PartSelectPanel from './PartSelectPanel';
import ImportPanel from './ImportPanel';
import {formatDateTime, formatAmount, conventEnumValueToString} from '../utils';
import {currency} from '../Enum';
import moment from 'moment';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const {Description} = DescriptionList;
const width = {
    width: '100%'
};

class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
        details: [],
        isSubmitting: false,
        hasOperat: false,
        showPartSelectPanel: false,
        showImportPanel: false
    }
    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
        else if(this.props.initDate.brands.length === 1)
            this.onChange(this.props.initDate.brands[0].value, 'brandId');
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details.map(v => Object.assign({}, v, {
                            isDealerUser: this.props.isDealerUser
                        }))
                    });
                else
                    this.setState({
                        loading: false
                    });
            });
    }
    setRowClassName(record) {
        if(record.isChange)
            return styles.rowStyle;
        if(record.isEstimated && !record.isDealerUser)
            return styles.rowStyle;
    }
    onChangeQuantity= (id, name, value) => {
        const detaileds = this.state.details || [];
        const tmp = detaileds.map(d => {
            const index = detaileds.findIndex(v => v.partId === id);
            if(d.partId === id && index >= 0)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onSelectpartOrderPlan = record => {
        this.setState({
            showpartOrderPlanSelectPanel: false,
            hasOperat: true,
            data: Object.assign({}, this.state.data, {
                partOrderPlanId: record.id,
                partOrderPlanCode: record.code,
                partOrderPlanName: record.name
            })
        });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onSubmit = () => {
        const {data, details} = this.state;
        const isValid = newOrUpdateOrderValidator(data) && addOrUpdateValidator(details);
        if(!isValid) {
            this.setState({
                validate: true,
                loading: false
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data, details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    };
    onClickSearchPartBtn= () => {
        if(!this.state.data.brandId) {
            message.warning(formatMessage({
                id: 'validator.message.required',
                defaultMessage: '请先选择品牌!'
            }));
            return;
        }
        this.setState({showPartSelectPanel: true});
    }
    onClickImportBtn = () => {
        if(!this.state.data.brandId) {
            message.warning(formatMessage({
                id: 'validator.message.required',
                defaultMessage: '请先选择品牌!'
            }));
            return;
        }
        this.setState({showImportPanel: true});
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onClosePartSelectPanel= () => {
        this.setState({showPartSelectPanel: false});
    }
    onSelectAddedPart = record => {
        const addedItems = this.state.details || [];
        record.forEach(v => {
            const index = addedItems.findIndex(r => r.partId === v.id);
            if(index === -1)
                addedItems.push({
                    id: uuid(),
                    partId: v.id,
                    partCode: v.code,
                    partName: v.name,
                    productCategoryCode: v.productCategoryCode,
                    minPackSize: v.minPackSize,
                    unit: v.unit,
                    price: v.price,
                    n2Quantity: v.minPackSize,
                    n3Quantity: 0,
                    n4Quantity: 0,
                    isDealerUser: this.props.isDealerUser,
                    partReplacementCode: v.partReplacementCode
                });
        });
        this.setState({
            details: [...addedItems],
            showPartSelectPanel: false,
            hasOperat: true
        });
    }
    onImportChange = records => {
        if(records.payload) {
            const stocks = [];
            records.payload.content.forEach(v => {
                const index = stocks.findIndex(r => r.partId === v.partId);
                if(index === -1)
                    stocks.push({
                        id: uuid(),
                        partId: v.partId,
                        partCode: v.partCode,
                        partName: v.partName,
                        productCategoryCode: v.productCategoryCode,
                        minPackSize: v.minPackSize,
                        unit: v.unit,
                        price: v.price,
                        n2Quantity: v.n2Quantity ? v.n2Quantity : 0,
                        n3Quantity: v.n3Quantity ? v.n3Quantity : 0,
                        n4Quantity: v.n4Quantity ? v.n4Quantity : 0,
                        isChange: v.isChange,
                        isDealerUser: this.props.isDealerUser,
                        partReplacementCode: v.partReplacementCode
                    });
            });
            this.setState({
                details: [...stocks],
                hasOperat: true,
                showImportPanel: false
            });
        }
    }
    onDeleteAddedItem = e => {
        const addedItemId = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== addedItemId);
        this.setState({
            details: [...tmp],
            hasOperat: true
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }

    render() {
        const {data, details} = this.state;
        const validateBrandId = !data.brandId && this.state.validate ? 'error' : null;
        if(this.props.brands.length === 1 && !this.props.id)
            data.brandId = this.props.brands[0].value;
        const totalVariety = this.state.details.filter(o => o.n2Quantity > 0 || o.n3Quantity > 0 || o.n4Quantity > 0).length;
        const totalN2Variety = this.state.details.filter(o => o.n2Quantity > 0).length;
        const totalN3Variety = this.state.details.filter(o => o.n3Quantity > 0).length;
        const totalN4Variety = this.state.details.filter(o => o.n4Quantity > 0).length;
        let totalQuantity = 0;
        let totalN2Quantity = 0;
        let totalN3Quantity = 0;
        let totalN4Quantity = 0;
        let totalFee = 0;
        let totalN2Fee = 0;
        let totalN3Fee = 0;
        let totalN4Fee = 0;
        this.state.details.forEach(o => {
            totalQuantity += (o.n2Quantity + o.n3Quantity + o.n4Quantity);
            totalN2Quantity += o.n2Quantity;
            totalN3Quantity += o.n3Quantity;
            totalN4Quantity += o.n4Quantity;
            totalFee += (o.n2Quantity + o.n3Quantity + o.n4Quantity) * o.price;
            totalN2Fee += o.n2Quantity * o.price;
            totalN3Fee += o.n3Quantity * o.price;
            totalN4Fee += o.n4Quantity * o.price;
        });

        const brand = this.props.brands.filter(o => o.value === data.brandId);
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            width: 200,
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
            width: 350,
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.n2Quantity',
                defaultMessage: 'N+2月订购数量'
            }),
            dataIndex: 'n2Quantity',
            width: 180,
            render: (text, record) => {
                const validate = ((record.n2Quantity === 0 && record.n3Quantity === 0 && record.n4Quantity === 0) ||
                (text > 0 && text % record.minPackSize > 0)) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="n2Quantity"
                            min={0}
                            precision={0}
                            defaultValue={0}
                            style={width}
                            value={record.n2Quantity}
                            onBlur={value => this.onChangeQuantity(record.partId, 'n2Quantity', value)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.n3Quantity',
                defaultMessage: 'N+3月订购数量'
            }),
            dataIndex: 'n3Quantity',
            width: 180,
            render: (text, record) => {
                const validate = ((record.n2Quantity === 0 && record.n3Quantity === 0 && record.n4Quantity === 0) ||
                (text > 0 && text % record.minPackSize > 0)) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="n3Quantity"
                            min={0}
                            precision={0}
                            defaultValue={0}
                            style={width}
                            value={record.n3Quantity}
                            onBlur={value => this.onChangeQuantity(record.partId, 'n3Quantity', value)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.n4Quantity',
                defaultMessage: 'N+4月订购数量'
            }),
            dataIndex: 'n4Quantity',
            width: 200,
            render: (text, record) => {
                const validate = ((record.n2Quantity === 0 && record.n3Quantity === 0 && record.n4Quantity === 0) ||
                (text > 0 && text % record.minPackSize > 0)) && this.state.validate ? {validateStatus: 'error'} : null;
                return (
                    <FormItem {...validate}>
                        <WrappedInputNumber
                            name="n4Quantity"
                            min={0}
                            precision={0}
                            defaultValue={0}
                            style={width}
                            value={record.n4Quantity}
                            onBlur={value => this.onChangeQuantity(record.partId, 'n4Quantity', value)} />
                    </FormItem>
                );
            }
        }, {
            title: formatMessage({
                id: 'newPanel.column.productCategoryCode',
                defaultMessage: '适用车型'
            }),
            width: 200,
            dataIndex: 'productCategoryCode',
            render: text => <Ellipsis tooltip fullWidthRecognition length={20}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'newPanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            width: 100,
            dataIndex: 'minPackSize',
            
        }, {
            title: formatMessage({
                id: 'newPanel.column.unit',
                defaultMessage: '计量单位'
            }),
            width: 100,
            dataIndex: 'unit',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partPrice',
                defaultMessage: '备件单价'
            }),
            dataIndex: 'price',
            width: 150,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.partReplacementCode',
                defaultMessage: '替换件编号'
            }),
            width: 250,
            dataIndex: 'partReplacementCode',
        }, {
            title: details && details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteAddedItem}>{formatMessage({
                id: 'newPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        const submitable = !hasPermissions(PERMISSIONS.add, this.props.permission) || !hasPermissions(PERMISSIONS.update, this.props.permission);
        const warningmessage = (
            <div>
                <Row>
                    <Col className={styles.message}>{formatMessage({
                        id: 'newPanel.alert.message1',
                        defaultMessage: '蓝色高亮，表示导入的数据自动向上取最小包装的整数倍'
                    })}</Col>
                </Row>
                <Row>
                    <Col className={styles.message}>{formatMessage({
                        id: 'newPanel.alert.message2',
                        defaultMessage: '红色高亮，表示是暂估价'
                    })}</Col>
                </Row>
            </div>
            
        );
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card title={formatMessage({
                            id: 'newPanel.column.partOrderPlan',
                            defaultMessage: '备件需求计划单'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.code || '尚未生成'}
                                    </FormItem>
                                </Col>
                                {this.props.initDate.brands.length !== 1 &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.brandId',
                                        defaultMessage: '品牌'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={validateBrandId}
                                    required>
                                        <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.orderPlanYear',
                                        defaultMessage: '计划年份'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.orderPlanYear || moment().add(2, 'months').format('YYYY')}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.orderPlanMonth',
                                        defaultMessage: '计划月份'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.orderPlanMonth || moment().add(2, 'months').format('M')}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })}{...FORM_OPTIONS.item}>
                                        { brand.length > 0 ? conventEnumValueToString(currency, brand[0].currency) : '' || ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'newPanel.operation.totalFee',
                                        defaultMessage: '总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}{...FORM_OPTIONS.item}>
                                        {totalQuantity || ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.totalVariety',
                                        defaultMessage: '总品种数'
                                    })}{...FORM_OPTIONS.item}>
                                        {totalVariety || ''}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.createTime',
                                        defaultMessage: '提报日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime || moment().toISOString(), DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={formatMessage({
                                id: 'editPanel.card.title.detail',
                                defaultMessage: '备件需求计划清单'
                            })}
                            extra={<div>
                                <Button size="small" onClick={this.onClickImportBtn}>
                                    {formatMessage({
                                        id: 'newPanel.operation.newDetail',
                                        defaultMessage: '导入清单'
                                    })}
                                </Button>
                                <Button size="small" onClick={this.onClickSearchPartBtn}>
                                    {formatMessage({
                                        id: 'updatePanel.part.addDetail',
                                        defaultMessage: '新增清单'
                                    })}
                                </Button>
                            </div>}>
                            {
                                details.length > 0 && <Alert
                                    className={styles.alertStyle}
                                    showIcon
                                    type="warning"
                                    message={warningmessage} />
                            }
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={colums}
                                dataSource={details}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                scroll={{
                                    x: 'max-content',
                                    y: 600
                                }}
                                size="small"
                                bordered={true}
                                footer={() => <div>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Quantity',
                                                defaultMessage: 'N+2月订购数量汇总'
                                            })}>{totalN2Quantity}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Quantity',
                                                defaultMessage: 'N+3月订购数量汇总'
                                            })}>{totalN3Quantity}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Quantity',
                                                defaultMessage: 'N+4月订购数量汇总'
                                            })}>{totalN4Quantity}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Fee',
                                                defaultMessage: 'N+2月订购金额汇总'
                                            })}>{formatAmount(totalN2Fee)}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Fee',
                                                defaultMessage: 'N+3月订购金额汇总'
                                            })}>{formatAmount(totalN3Fee)}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Fee',
                                                defaultMessage: 'N+4月订购金额汇总'
                                            })}>{formatAmount(totalN4Fee)}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                    <Row className={styles.alertMargin}>
                                        <DescriptionList>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN2Variety',
                                                defaultMessage: 'N+2月订购品种汇总'
                                            })}>{totalN2Variety}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN3Variety',
                                                defaultMessage: 'N+3月订购品种汇总'
                                            })}>{totalN3Variety}
                                            </Description>
                                            <Description term={formatMessage({
                                                id: 'newPanel.operation.totalN4Variety',
                                                defaultMessage: 'N+4月订购品种汇总'
                                            })}>{totalN4Variety}
                                            </Description>
                                        </DescriptionList>
                                    </Row>
                                </div>}/>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'editPanel.save',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                {
                    this.state.showPartSelectPanel &&
                         <PartSelectPanel
                             dealerId={this.props.initDate.company.id}
                             brandId={data.brandId}
                             onCancel={this.onClosePartSelectPanel}
                             onSelect={this.onSelectAddedPart} />
                }
                {
                    this.state.showImportPanel &&
                        <ImportPanel
                            dealerId={this.props.initDate.company.id}
                            brandId={data.brandId}
                            selectKey={data.warehouseId}
                            onCancel={this.onCloseImportPanel}
                            onImportChange={this.onImportChange} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    initDate: PropTypes.object.isRequired,
    permission: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    isDealerUser: PropTypes.bool
};

import {connect} from 'react-redux';
import routes from './routes';
import {
    tableSearch,
    onSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getInitDate = selectorFactory(['page', 'domainData', 'initData']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: item.code,
                currency: item.currency
            }))
            : [];
    }
);
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permission: getPermissions(state),
    initDate: getInitDate(state),
    brands: getBrands(state),
});

const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: (data, details) => dispatch(onSubmit(data, details)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
